import {Component, OnInit, ViewChild} from '@angular/core';
import {BaseGridComponent, BaseService} from '@sb/base';
import {SFCheckboxWidgetSchema, SFSchema, SFTextareaWidgetSchema} from '@delon/form';
import {NzMessageService, NzModalService, NzTabChangeEvent} from 'ng-zorro-antd';
import {RmMenuSearchForm} from '../entity/rm-menu-search-form';
import {STColumn} from '@delon/abc';
import {RmMenu} from '../entity/rm-menu';
import {BaseTreeService} from '@sb/base/core/service/base-tree.service';
import {RmMenuTreeService} from '../service/rm-menu-tree.service';
import {RmMenuTreeNode} from '../entity/rm-menu-tree-node';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {DomSanitizer} from '@angular/platform-browser';
import {RmMenuTreePanelComponent} from '../rm-menu-tree-panel/rm-menu-tree-panel.component';
import {NzTreeNode} from 'ng-zorro-antd/core/tree/nz-tree-base-node';
import {SFSchemaEnumType} from '@delon/form/src/schema';
import {SysCodeService} from '../../../sys/sys-code/service/sys-code.service';
import {map} from 'rxjs/operators';


@Component({
    selector: 'rm-menu',
    templateUrl: './rm-menu.component.html',
    styleUrls: ['./rm-menu.component.less'],
    providers: [
        {
            provide: BaseTreeService,
            useClass: RmMenuTreeService
        },
        {
            provide: BaseService,
            useClass: RmMenuTreeService
        }
    ]
})
export class RmMenuComponent implements OnInit {

    typeIcon = {
        APPLICATION: 'dr:hy-application',
        MENU: 'dr:hy-menu',
        MODULE: 'dr:hy-module'
    };

    baseParam: RmMenu = {};

    searchForm: RmMenuSearchForm = {
        parentId: '-1'
    };

    @ViewChild(BaseGridComponent, {static: false})
    baseGrid: BaseGridComponent;

    @ViewChild(RmMenuTreePanelComponent, {static: true})
    rmMenuTreePanel: RmMenuTreePanelComponent;
    schema: SFSchema = {
        properties: {
            name: {
                type: 'string',
                title: '名称',
                minLength: 2
            },
            type: {
                type: 'string',
                title: '类型',
                enum: [
                    {
                        value: 'APPLICATION',
                        label: '应用'
                    }, {
                        value: 'MENU',
                        label: '菜单'
                    }, {
                        value: 'MODULE',
                        label: '目录'
                    }, {
                        value: 'PERMISSION',
                        label: '权限'
                    }
                ],
                readOnly: true,
                default: 'APPLICATION'
            },
            code: {
                type: 'string',
                title: '编码'
            },
            applicationType: {
                type: 'string',
                title: '应用类型',
                enum: [
                    {
                        value: 'WEB',
                        label: 'web'
                    },
                    {
                        value: 'APP',
                        label: 'app'
                    }
                ],
                default: 'WEB',
                ui: {
                    widget: 'select',
                    visibleIf: {
                        type: ['APPLICATION']
                    }
                }
            },
            openType: {
                type: 'string',
                title: '打开方式',
                enum: [
                    {
                        value: 'IFRAME',
                        label: '普通打开'
                    },
                    {
                        value: 'OPEN',
                        label: '新窗口打开'
                    }
                ],
                default: 'IFRAME',
                ui: {
                    widget: 'select',
                    visibleIf: {
                        type: ['MENU']
                    }
                }
            },
            urlType: {
                type: 'string',
                title: '地址类型',
                enum: [
                    {
                        value: 'ANGULAR',
                        label: '系统地址'
                    },
                    {
                        value: 'ABSOLUTE',
                        label: '绝对地址'
                    },
                    {
                        value: 'RELATIVE',
                        label: '相对地址'
                    }
                ],
                default: 'RELATIVE',
                ui: {
                    widget: 'select',
                    visibleIf: {
                        type: ['MENU']
                    }
                }
            },
            url: {
                type: 'string',
                title: '功能访问地址',
                ui: {
                    widget: 'textarea',
                    autosize: {
                        minRows: 3,
                        maxRows: 5
                    },
                    class: 'custom-break-all',
                    visibleIf: {
                        type: ['MENU']
                    }
                } as SFTextareaWidgetSchema,
                description: '如果是angular模块，可以使用|进行分隔参数，例：...Module|code=abc&name=456。 模块代码通过activatedRoute.snapshot.data.param获取对象值！'
            },
            useDefaultHeader: {
                type: 'boolean',
                title: '使用默认导航栏',
                ui: {
                    checkedChildren: '使用',
                    unCheckedChildren: '不使用',
                    visibleIf: {
                        type: ['APPLICATION']
                    }
                },
                default: true
            },
            iconId: {
                type: 'string',
                title: '菜单图标',
                ui: {
                    widget: 'rm-menu-icon-select-alain',
                    visibleIf: {
                        type: (value) => {
                            return value && value !== 'PERMISSION';
                        }
                    }
                }
            },
            active: {
                type: 'boolean',
                title: '是否启用',
                default: true,
                ui: {
                    checkedChildren: '启用',
                    unCheckedChildren: '停用',
                    visibleIf: {
                        type: ['MENU']
                    }
                }
            },
            usePermission: {
                type: 'boolean',
                title: '使用权限',
                default: false,
                ui: {
                    checkedChildren: '启用',
                    unCheckedChildren: '停用',
                    visibleIf: {
                        type: ['MENU']
                    }
                }
            },
            permissionCode: {
                type: 'string',
                title: '权限编码',
                ui: {
                    visibleIf: {
                        usePermission: [true]
                    }
                }
            },
            createDefaultPermission: {
                type: 'string',
                title: '快捷创建权限',
                ui: {
                    visibleIf: {
                        permissionCode: value => !!value
                    },
                    asyncData: (): Observable<SFSchemaEnumType[]> => {
                        return this.sysCodeService.getComboBox('DEFAULT_PERMISSION_CODE').pipe(map(value => {
                            if (value.success) {
                                return value.message.map((combox) => {
                                    return {
                                        label: combox.name,
                                        value: combox.code,
                                    } as SFSchemaEnumType;
                                });
                            }
                        }));
                    },
                    widget: 'checkbox',
                    checkAll: true,
                } as SFCheckboxWidgetSchema,
                default: []
            },
            remark: {
                type: 'string',
                title: '备注',
                ui: {
                    widget: 'textarea',
                    autosize: {
                        minRows: 2,
                        maxRows: 8
                    },
                    visibleIf: {
                        type: ['MENU']
                    }
                } as SFTextareaWidgetSchema
            }
        },
        required: ['name', 'type', 'url', 'urlType', 'openType', 'active', 'applicationType']
    } as SFSchema;
    activateNzTreeNode: NzTreeNode;
    activateTreeNode: RmMenuTreeNode;
    columns: STColumn[] = [
        {
            title: '',
            type: 'checkbox',
            index: 'id',
            width: '7%',
            className: 'text-center word-wrap'
        }, {
            title: '名称',
            index: 'name',
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '编码',
            index: 'code',
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '打开方式',
            index: 'openType',
            format: v => {
                if (!v) {
                    return '';
                }
                switch (v.openType) {
                    case 'IFRAME':
                        return '普通打开';
                    case 'OPEN':
                        return '新窗口打开';
                    default:
                        return '';
                }
            },
            iif: () => this.activateTreeNode.type !== 'root',
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '应用类型',
            index: 'applicationType',
            format: v => {
                if (v.applicationType === 'WEB') {
                    return 'web';
                } else if (v.type === 'APP') {
                    return 'app';
                } else {
                    return '';
                }
            },
            iif: () => this.activateTreeNode.type === 'root',
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '类型',
            index: 'type',
            format: v => {
                if (v.type === 'APPLICATION') {
                    return '应用';
                } else if (v.type === 'MENU') {
                    return '菜单';
                } else {
                    return '目录';
                }
            },
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '操作区',
            className: 'text-center word-wrap',
            width: '18%',
            buttons: []
        }
    ] as STColumn[];
    tabIndex = 0;
    showApplicationTab: boolean;
    showModuleMenuTab: boolean;
    showPermissionTab: boolean;
    showDetailTab: boolean;
    showGrid = true;


    searchConfig: { [key: string]: any } = {
        searchPermission: false
    };
    settingOptions = [
        {label: '显示权限', value: 'permission'}
    ];

    constructor(
        private message: NzMessageService,
        private menuService: RmMenuTreeService,
        private sysCodeService: SysCodeService,
        private sanitizer: DomSanitizer,
        private modal: NzModalService) {
    }

    ngOnInit(): void {
    }

    selectNode(nzTreeNode: NzTreeNode): void {
        const treeNode = nzTreeNode.origin as RmMenuTreeNode;
        // 修改 tab显示
        let title = '';
        let change = true;
        if (this.activateTreeNode && this.activateTreeNode.type === treeNode.type) {
            if (treeNode.type === 'MENU') {
            } else {
                change = false;
            }
        }
        if (change) {
            if (treeNode.type === 'root') {
                this.showApplicationTab = true;
                this.showDetailTab = false;
                this.showModuleMenuTab = false;
                this.showPermissionTab = false;
                title = '应用';
            } else if (treeNode.type === 'APPLICATION' || treeNode.type === 'MODULE') {
                this.showApplicationTab = false;
                this.showDetailTab = true;
                this.showModuleMenuTab = true;
                this.showPermissionTab = false;
                title = '模块 / 菜单';
            } else if (treeNode.type === 'MENU') {
                this.showApplicationTab = false;
                this.showModuleMenuTab = false;
                this.showDetailTab = true;
                this.showPermissionTab = treeNode.data.usePermission;

                title = '详情';
            } else if (treeNode.type === 'PERMISSION') {
                this.showApplicationTab = false;
                this.showModuleMenuTab = false;
                this.showPermissionTab = false;
                this.showDetailTab = true;
                title = '详情';
            }
            this.tabIndex = 0;
        }

        this.activateTreeNode = treeNode;

        this.activateNzTreeNode = nzTreeNode;

        this.searchForm.parentId = treeNode.key;

        this.reloadGrid(title);
    }

    onDataReload() {
        this.rmMenuTreePanel.reloadNode(this.activateNzTreeNode.parentNode.key);
    }

    recordWrapper(rmMenu: RmMenu): RmMenu {
        if (this.activateTreeNode.key !== rmMenu.id) {
            Object.assign(rmMenu, {parentId: this.activateTreeNode.key});
        }
        delete rmMenu.iconData;
        return rmMenu;
    }

    beforeRemove(menus: RmMenu[]): Observable<boolean> {
        const subject = new BehaviorSubject(false);
        for (let i = 0; i < menus.length; i++) {
            const menu = menus[i];
            if (menu.type === 'APPLICATION' || menu.type === 'MODULE') {
                this.modal.confirm({
                    nzTitle: '删除提示',
                    nzContent: '删除应用或目录会同时删除当前节点下的所有菜单，是否确定删除?',
                    nzOnOk: () => {
                        subject.next(true);
                        subject.complete();
                    }
                }, 'warning');
                break;
            }

            if (i === menus.length - 1) {
                return of(true);
            }
        }
        return subject;
    }

    itemClick(menu: RmMenu) {
        this.rmMenuTreePanel.triggerClick(menu.id);
    }

    getSvgHtml(picture: string) {
        return this.sanitizer.bypassSecurityTrustHtml(picture);
    }

    nzSelectChange(changeEvent: NzTabChangeEvent) {
        const title = changeEvent.tab.nzTitle as string;
        this.reloadGrid(title);
    }

    reloadGrid(title: string) {
        if (!title) {
            return;
        }
        if (title === '详情') {
            this.updateDetailSchema();
            this.showGrid = false;
        } else {
            this.showGrid = true;
            if (title === '应用') {
                this.baseParam.type = 'APPLICATION';
            } else if (title === '模块') {
                this.baseParam.type = 'MODULE';
            } else if (title === '模块 / 菜单') {
                this.baseParam.type = undefined;
            } else if (title === '菜单') {
                this.baseParam.type = 'MENU';
            } else if (title === '权限') {
                this.baseParam.type = 'PERMISSION';
            }
            this.updateSchema();
            if (this.baseGrid) {
                this.baseGrid.baseParam = this.baseParam;
                if (this.baseGrid.showType === 'table' && this.baseGrid.st) {
                    this.baseGrid.st.clear();
                    this.baseGrid.st.resetColumns({emitReload: false}).then();
                }
                this.baseGrid.reload();
            }
        }
    }

    updateSchema(): void {
        let readOnly = false;
        if (this.activateTreeNode.type === 'root') {
            this.schema.properties.type.enum = [
                {
                    value: 'APPLICATION',
                    label: '应用'
                }];
            readOnly = true;
        } else if (this.activateTreeNode.type === 'APPLICATION' || this.activateTreeNode.type === 'MODULE') {
            this.schema.properties.type.default = 'MENU';
            this.schema.properties.type.enum = [
                {
                    value: 'MODULE',
                    label: '目录'
                },
                {
                    value: 'MENU',
                    label: '菜单'
                }];
            readOnly = false;
        } else if (this.activateTreeNode.type === 'MENU' || this.activateTreeNode.type === 'MODULE') {
            this.schema.properties.type.enum = [
                {
                    value: 'PERMISSION',
                    label: '权限'
                }];
            readOnly = true;
        }
        this.schema.properties.type.readOnly = readOnly;
    }

    updateDetailSchema(): void {
        this.schema.properties.type.enum = [
            {
                value: 'APPLICATION',
                label: '应用'
            }, {
                value: 'MODULE',
                label: '目录'
            }, {
                value: 'MENU',
                label: '菜单'
            }, {
                value: 'PERMISSION',
                label: '权限'
            }];
        this.schema.properties.type.readOnly = true;
    }

    detailClose($event: boolean) {
        const nodeId = this.activateTreeNode.key;
        this.rmMenuTreePanel.reloadNode(this.activateNzTreeNode.parentNode.key).subscribe(value => {
            this.rmMenuTreePanel.triggerClick(nodeId);
        });
    }

    settingChange(value: any[]) {
        value.forEach(item => {
            if (item.value === 'permission') {
                this.searchConfig.searchPermission = item.checked;
            }
        });
        // 刷新节点
        this.rmMenuTreePanel.reload().subscribe(res => {
            this.rmMenuTreePanel.triggerClick(this.activateTreeNode.key);
        });
    }

}
